<template>
  <div class="flex h-screen bg-slate-50" style="min-width: 0; overflow: hidden;">
    <!-- 左侧边栏 -->
    <div id="sidebar" class="sidebar sidebar-expanded bg-white shadow-xl border-r border-slate-200 flex flex-col flex-shrink-0" :class="{ 'sidebar-collapsed': !sidebarOpen }">
      <!-- 应用标题 -->
      <div class="p-6 border-b border-slate-200">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center shadow-lg">
              <i class="fas fa-brain text-white text-lg"></i>
            </div>
            <div class="fade-text" :class="{ 'hidden': !sidebarOpen }">
              <h1 class="font-bold text-xl bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">博沃智慧</h1>
              <p class="text-xs text-slate-500">智能助手</p>
            </div>
          </div>
          <button @click="sidebarOpen = !sidebarOpen" class="p-2 rounded-lg hover:bg-slate-100 transition-colors">
            <i class="fas fa-bars text-slate-600"></i>
          </button>
        </div>
      </div>

      <!-- Robot选择器 -->
      <div class="p-4 border-b border-slate-200">
        <div class="mb-3">
          <label class="block text-sm font-medium text-slate-700 mb-2 fade-text" :class="{ 'hidden': !sidebarOpen }">选择Robot</label>
          <select v-model="selectedRobot" class="w-full p-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500">
            <option value="robot1">机器人1</option>
            <option value="robot2">机器人2</option>
            <option value="tech-docs">技术文档库问答</option>
            <option value="work-docs">工作资料库问答</option>
            <option value="study-docs">学习资料库问答</option>
          </select>
        </div>
      </div>

      <!-- 对话记录 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar has-tooltip">
        <div class="p-4">
          <div class="flex items-center justify-between mb-4">
            <h3 class="fade-text font-semibold text-slate-700" :class="{ 'hidden': !sidebarOpen }">对话历史</h3>
            <button @click="createNewConversation" class="fade-text p-2 rounded-lg bg-indigo-500 text-white hover:bg-indigo-600 transition-colors" :class="{ 'hidden': !sidebarOpen }">
              <i class="fas fa-plus text-sm"></i>
            </button>
          </div>

          <!-- 搜索框 -->
          <div class="search-box mb-4 fade-text" :class="{ 'hidden': !sidebarOpen }">
            <div class="relative">
              <input 
                v-model="searchQuery" 
                type="text" 
                placeholder="搜索对话..." 
                class="w-full p-2 pl-8 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 text-sm"
              />
              <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-slate-400 text-xs"></i>
            </div>
          </div>

          <!-- 对话列表 -->
          <div class="space-y-2">
            <div 
              v-for="conversation in filteredConversations" 
              :key="conversation.id"
              @click="selectConversation(conversation)"
              class="conversation-item group relative p-4 rounded-xl bg-slate-50 hover:bg-slate-100 cursor-pointer transition-all duration-200"
              :class="{ 'bg-blue-50 border-l-4 border-blue-500': selectedConversation?.id === conversation.id }"
            >
              <div class="flex items-start justify-between">
                <div class="fade-text flex-1">
                  <div class="flex items-center space-x-2 mb-1">
                    <i :class="getConversationIcon(conversation.type)" class="text-sm"></i>
                    <p class="font-medium text-slate-800 text-sm">{{ conversation.title }}</p>
                  </div>
                  <p class="text-xs text-slate-500">{{ formatDate(conversation.created_at) }}</p>
                </div>
                <div class="fade-text flex space-x-1">
                  <button class="p-1 rounded hover:bg-red-100 text-red-500 transition-all opacity-0 group-hover:opacity-100" title="删除对话记录" @click.stop="deleteConversation(conversation.id)">
                    <i class="fas fa-trash text-xs"></i>
                  </button>
                  <button class="p-1 rounded hover:bg-blue-100 text-blue-500 transition-all opacity-0 group-hover:opacity-100" title="下载对话记录" @click.stop="downloadConversation(conversation)">
                    <i class="fas fa-download text-xs"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户信息 -->
      <div class="p-4 border-t border-slate-200 has-tooltip">
        <div class="flex items-center space-x-3">
          <div class="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center shadow-lg user-avatar">
            <i class="fas fa-user text-white text-lg"></i>
          </div>
          <div class="fade-text flex-1" :class="{ 'hidden': !sidebarOpen }">
            <p class="font-semibold text-slate-800">{{ authStore.username }}</p>
            <p class="text-xs text-slate-500">专业版用户</p>
          </div>
          <div class="fade-text flex space-x-1 user-actions" :class="{ 'hidden': !sidebarOpen }">
            <button @click="goToSettings" class="p-2 rounded-lg hover:bg-slate-100 transition-colors" title="系统设置">
              <i class="fas fa-cog text-slate-600"></i>
            </button>
            <button @click="handleLogout" class="p-2 rounded-lg hover:bg-slate-100 transition-colors" title="退出登录">
              <i class="fas fa-sign-out-alt text-slate-600"></i>
            </button>
          </div>
        </div>
        <div class="tooltip">用户信息</div>
      </div>
    </div>

    <!-- 中间问答界面 -->
    <div class="flex-1 flex flex-col bg-white overflow-hidden" style="width: 40%; min-width: 0;">
      <!-- 聊天区域 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar p-6 space-y-6" id="chatArea">
        <div v-if="messages.length === 0" class="flex items-center justify-center h-full">
          <div class="text-center py-12">
            <div class="w-16 h-16 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center mx-auto mb-4">
              <i class="fas fa-comments text-white text-2xl"></i>
            </div>
            <h3 class="text-xl font-semibold text-slate-800 mb-2">开始新的对话</h3>
            <p class="text-slate-600">请输入您的问题，我将为您提供专业的回答</p>
          </div>
        </div>
        
        <div v-for="message in messages" :key="message.id" class="chat-message">
          <!-- 用户消息 -->
          <div v-if="message.role === 'user'" class="flex justify-end">
            <div class="flex items-start space-x-3 max-w-[80%]">
              <div class="bg-gradient-to-r from-blue-500 to-indigo-600 rounded-2xl rounded-br-sm p-4 shadow-lg">
                <p class="text-white text-sm leading-relaxed">{{ message.content }}</p>
                <div class="timestamp user-timestamp text-blue-200 mt-2 text-xs">{{ formatTime(message.created_at) }}</div>
              </div>
              <div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-400 to-indigo-500 flex items-center justify-center shadow-md">
                <span class="text-white text-sm">{{ authStore.username?.charAt(0).toUpperCase() }}</span>
              </div>
            </div>
          </div>
          
          <!-- 机器人消息 -->
          <div v-else class="flex justify-start">
            <div class="flex items-start space-x-3 max-w-[92%]">
              <div class="w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center shadow-md">
                <i class="fas fa-robot text-white text-sm"></i>
              </div>
              <div class="glass-effect rounded-2xl p-6 shadow-xl border border-slate-200">
                <div class="mb-4">
                  <p class="text-slate-700 text-sm leading-relaxed mb-3">
                    我正在处理您的问题："{{ message.content }}"
                  </p>
                  <div class="timestamp text-xs text-slate-500">{{ formatTime(message.created_at) }}</div>
                </div>
                
                <!-- 进度条 -->
                <div class="mb-6">
                  <div class="flex justify-between text-xs text-slate-500 mb-2">
                    <span>处理进度</span>
                    <span id="progressText">{{ progress }}%</span>
                  </div>
                  <div class="w-full bg-slate-200 rounded-full h-2">
                    <div class="progress-bar" :style="{ width: progress + '%' }"></div>
                  </div>
                </div>
                
                <!-- Todo List -->
                <div class="space-y-3">
                  <div 
                    v-for="task in processingTasks" 
                    :key="task.id"
                    class="todo-item processing-node p-4 rounded-xl border-2 bg-white cursor-pointer"
                    :class="getTaskClasses(task)"
                    :data-step="task.id"
                    :data-task="task.id"
                    @click="handleTaskClick(task)"
                  >
                    <div class="flex items-center justify-between">
                      <div class="flex items-center space-x-3">
                        <div class="w-6 h-6 rounded-full flex items-center justify-center" :class="getTaskIconClasses(task)">
                          <i v-if="task.status === 'processing'" class="loading-dots">
                            <span></span>
                            <span></span>
                            <span></span>
                          </i>
                          <i v-else :class="getTaskIcon(task)" class="text-white text-xs"></i>
                        </div>
                        <div>
                          <p class="font-medium text-slate-800">{{ task.title }}</p>
                          <p class="text-xs text-slate-500 mt-1">{{ task.description }}</p>
                        </div>
                      </div>
                      <span class="text-xs font-medium" :class="getTaskStatusClasses(task)">
                        {{ getTaskStatus(task) }}
                      </span>
                    </div>
                    <div class="task-details" :class="{ 'show': task.showDetails }">
                      <h4>{{ getTaskDetailTitle(task) }}</h4>
                      <ul>
                        <li v-for="(item, index) in getTaskDetailItems(task)" :key="index">{{ item }}</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="border-t border-slate-200 p-4 bg-white">
        <div class="flex items-end space-x-3">
          <div class="flex-1">
            <textarea 
              v-model="newMessage"
              @keyup.enter.ctrl="sendMessage"
              class="w-full p-4 border-2 border-slate-200 rounded-xl resize-none focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-all"
              placeholder="输入您的问题..."
              rows="1"
              :disabled="isLoading"
            ></textarea>
            <!-- 附件选项 -->
            <div class="flex items-center justify-between mt-3">
              <div class="flex items-center space-x-2">
                <button @click="uploadImage" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="上传图片" title="上传图片">
                  <i class="fas fa-image text-slate-600"></i>
                </button>
                <button @click="uploadFile" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="上传文件" title="上传文件">
                  <i class="fas fa-file text-slate-600"></i>
                </button>
                <button @click="insertCodeSnippet" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="代码片段" title="代码片段">
                  <i class="fas fa-code text-slate-600"></i>
                </button>
                <div class="w-px h-6 bg-slate-300 mx-2"></div>
                <button @click="startVoiceInput" class="attachment-btn p-2 rounded-lg hover:bg-red-100 transition-all" :class="{ 'voice-recording': isRecording }" data-tooltip="语音输入" title="语音输入">
                  <i class="fas fa-microphone" :class="{ 'text-slate-600': !isRecording, 'text-white': isRecording }"></i>
                </button>
              </div>
              <div class="flex items-center space-x-2">
                <button @click="clearConversation" class="p-2 rounded-lg hover:bg-slate-100 transition-all" title="清空对话">
                  <i class="fas fa-trash text-slate-600"></i>
                </button>
                <span class="text-xs text-slate-400">按 Enter 发送</span>
                <button 
                  @click="sendMessage"
                  :disabled="isLoading || !newMessage.trim()"
                  class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white p-3 rounded-xl hover:from-indigo-600 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i v-if="isLoading" class="fas fa-spinner fa-spin"></i>
                  <i v-else class="fas fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧结果面板 -->
    <div class="bg-slate-50 border-l border-slate-200 flex flex-col overflow-hidden" style="width: 45%; min-width: 0;">
      <!-- 标题栏 -->
      <div class="bg-white border-b border-slate-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <h2 class="font-bold text-slate-800 text-lg">回答详情</h2>
            <p class="text-sm text-slate-500">展示模型处理过程和输出结果</p>
          </div>
          <div class="flex items-center space-x-2">
            <div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
          </div>
        </div>
      </div>

      <!-- 结果内容 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar p-6 space-y-4" id="resultArea">
        <div v-if="resultPanels.length === 0" class="flex items-center justify-center h-full">
          <div class="text-center">
            <div class="w-16 h-16 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center mx-auto mb-4 opacity-50">
              <i class="fas fa-chart-line text-white text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-slate-800 mb-2">等待处理结果</h3>
            <p class="text-slate-600">开始对话后，处理结果将在这里显示</p>
          </div>
        </div>

        <div 
          v-for="panel in resultPanels" 
          :key="panel.id"
          class="result-panel bg-white rounded-xl shadow-sm border border-slate-200 p-6 transition-all duration-300"
          :class="{ 'ring-2 ring-indigo-500 bg-indigo-50': panel.active }"
          :data-result="panel.id"
          :style="{ display: panel.visible ? 'block' : 'none' }"
          @click="handleResultPanelClick(panel)"
        >
          <div class="flex items-center justify-between mb-4">
            <h3 class="font-semibold text-slate-800 flex items-center">
              <div class="w-8 h-8 rounded-lg flex items-center justify-center mr-3" :class="panel.iconBg">
                <i :class="panel.icon" class="text-white"></i>
              </div>
              {{ panel.title }}
            </h3>
            <div class="flex items-center space-x-2">
              <span class="px-2 py-1 text-xs rounded-full" :class="panel.stepBadge">{{ panel.step }}</span>
              <span class="text-xs text-slate-400">{{ formatTime(panel.timestamp) }}</span>
              <span v-if="panel.extraInfo" class="text-xs ml-2" :class="panel.extraInfoClass">{{ panel.extraInfo }}</span>
            </div>
          </div>
          
          <div class="space-y-3" v-html="panel.content"></div>
        </div>
      </div>

      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 类型定义
interface Message {
  id: number
  role: 'user' | 'assistant'
  content: string
  created_at: Date
}

interface Conversation {
  id: number
  title: string
  created_at: Date
  type: 'knowledge' | 'data' | 'image' | 'code'
}

interface ProcessingTask {
  id: number
  title: string
  description: string
  status: 'pending' | 'processing' | 'completed'
  icon: string
  showDetails: boolean
  details: {
    title: string
    items: string[]
  }
}

interface ResultPanel {
  id: number
  title: string
  content: string
  icon: string
  iconBg: string
  step: string
  stepBadge: string
  timestamp: Date
  active: boolean
  visible: boolean
  extraInfo?: string
  extraInfoClass?: string
}

// 响应式数据
const sidebarOpen = ref(true)
const selectedRobot = ref('robot1')
const searchQuery = ref('')
const selectedConversation = ref<Conversation | null>(null)
const newMessage = ref('')
const isLoading = ref(false)
const messages = ref<Message[]>([])
const conversations = ref<Conversation[]>([])
const progress = ref(0)
const processingTasks = ref<ProcessingTask[]>([])
const resultPanels = ref<ResultPanel[]>([])

// 计算属性
const filteredConversations = computed(() => {
  if (!searchQuery.value) return conversations.value
  return conversations.value.filter(conv => 
    conv.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 方法
const getConversationIcon = (type: string) => {
  const icons = {
    'knowledge': 'fas fa-book-open text-blue-500',
    'data': 'fas fa-chart-line text-indigo-500',
    'image': 'fas fa-image text-green-500',
    'code': 'fas fa-code text-purple-500'
  }
  return icons[type as keyof typeof icons] || 'fas fa-comments text-slate-500'
}

const createNewConversation = () => {
  selectedConversation.value = null
  messages.value = []
  progress.value = 0
  processingTasks.value = []
  resultPanels.value = []
}

const selectConversation = (conversation: Conversation) => {
  selectedConversation.value = conversation
  loadConversation(conversation.type)
}

const loadConversation = (type: string) => {
  messages.value = []
  progress.value = 0
  processingTasks.value = []
  resultPanels.value = []
  
  switch(type) {
    case 'knowledge':
      loadKnowledgeConversation()
      break
    case 'data':
      loadDataConversation()
      break
    case 'image':
      loadImageConversation()
      break
    case 'code':
      loadCodeConversation()
      break
  }
}

const loadKnowledgeConversation = () => {
  const userMessage: Message = {
    id: 1,
    role: 'user',
    content: '深圳监测站有哪些分析方法可以分析地表水中铜？',
    created_at: new Date()
  }
  
  const assistantMessage: Message = {
    id: 2,
    role: 'assistant',
    content: '深圳监测站有哪些分析方法可以分析地表水中铜？',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('knowledge')
  startProcessing('knowledge')
}

const loadDataConversation = () => {
  const userMessage: Message = {
    id: 1,
    role: 'user',
    content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
    created_at: new Date()
  }
  
  const assistantMessage: Message = {
    id: 2,
    role: 'assistant',
    content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('data')
  startProcessing('data')
}

const loadImageConversation = () => {
  const userMessage: Message = {
    id: 1,
    role: 'user',
    content: '请分析这张臭氧变化趋势图',
    created_at: new Date()
  }
  
  const assistantMessage: Message = {
    id: 2,
    role: 'assistant',
    content: '请分析这张臭氧变化趋势图',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('image')
  startProcessing('image')
}

const loadCodeConversation = () => {
  const userMessage: Message = {
    id: 1,
    role: 'user',
    content: '请帮我分析这段Python代码的性能问题',
    created_at: new Date()
  }
  
  const assistantMessage: Message = {
    id: 2,
    role: 'assistant',
    content: '请帮我分析这段Python代码的性能问题',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('code')
  startProcessing('code')
}

const deleteConversation = (id: number) => {
  conversations.value = conversations.value.filter(conv => conv.id !== id)
  if (selectedConversation.value?.id === id) {
    createNewConversation()
  }
}

const downloadConversation = (conversation: Conversation) => {
  // 模拟下载功能
  console.log('下载对话:', conversation.title)
}

const sendMessage = async () => {
  if (!newMessage.value.trim() || isLoading.value) return

  const userMessage: Message = {
    id: Date.now(),
    role: 'user',
    content: newMessage.value,
    created_at: new Date()
  }

  messages.value.push(userMessage)
  isLoading.value = true

  try {
    // 初始化处理任务
    initializeProcessingTasks('general')
    
    // 模拟API调用和处理过程
    await startProcessing('general')
    
    const assistantMessage: Message = {
      id: Date.now() + 1,
      role: 'assistant',
      content: newMessage.value,
      created_at: new Date()
    }

    messages.value.push(assistantMessage)
    
    // 如果是新对话，保存到对话列表
    if (!selectedConversation.value) {
      const newConversation: Conversation = {
        id: Date.now(),
        title: newMessage.value.substring(0, 50) + (newMessage.value.length > 50 ? '...' : ''),
        created_at: new Date(),
        type: 'knowledge'
      }
      conversations.value.unshift(newConversation)
      selectedConversation.value = newConversation
    }
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    isLoading.value = false
    newMessage.value = ''
  }
}

const initializeProcessingTasks = (type: string) => {
  const taskConfig = {
    knowledge: [
      {
        id: 1,
        title: '1. 问题解析',
        description: '分析用户问题意图',
        icon: 'fas fa-search',
        details: {
          title: '问题解析流程',
          items: [
            '✓ 识别问题领域：环境监测技术',
            '✓ 提取关键实体：深圳监测站、地表水、铜、分析方法',
            '✓ 确定查询目标：获取具体的铜分析方法列表',
            '✓ 分析查询深度：需要包括技术参数和标准依据'
          ]
        }
      },
      {
        id: 2,
        title: '2. 知识检索',
        description: '检索内部知识库',
        icon: 'fas fa-database',
        details: {
          title: '知识检索流程',
          items: [
            '✓ 搜索国家标准库：GB 3838-2002等水质标准',
            '✓ 检索行业规范：HJ系列环境监测标准',
            '✓ 查询技术文档：水和废水监测分析方法',
            '✓ 筛选相关方法：过滤出铜的专项分析方法'
          ]
        }
      },
      {
        id: 3,
        title: '3. 互联网搜索',
        description: '搜索最新技术资料',
        icon: 'fas fa-globe',
        details: {
          title: '互联网搜索流程',
          items: [
            '✓ 搜索最新技术进展：深圳监测站技术设备更新',
            '✓ 查找行业动态：水质监测技术发展趋势',
            '✓ 收集实践案例：其他城市的先进经验',
            '✓ 整合技术资料：形成完整的技术参考'
          ]
        }
      },
      {
        id: 4,
        title: '4. 生成回复',
        description: '整理并生成最终回复',
        icon: 'fas fa-file-alt',
        details: {
          title: '回复生成流程',
          items: [
            '✓ 整合分析方法：汇总各种检测技术参数',
            '✓ 核验标准依据：确保引用最新的国家标准',
            '✓ 优化表达方式：按照重要性和实用性排序',
            '✓ 添加实用信息：包括检测限、适用范围等关键信息'
          ]
        }
      }
    ],
    data: [
      {
        id: 1,
        title: '1. 需求分析',
        description: '理解用户数据查询需求',
        icon: 'fas fa-search',
        details: {
          title: '需求分析流程',
          items: [
            '✓ 分析查询目标：深圳AQI趋势分析',
            '✓ 确定时间范围：最近一个月的数据',
            '✓ 识别数据类型：空气质量指数时间序列',
            '✓ 明确输出要求：趋势分析和可视化展示'
          ]
        }
      },
      {
        id: 2,
        title: '2. 数据查询',
        description: '查询环境监测数据库',
        icon: 'fas fa-database',
        details: {
          title: '数据查询流程',
          items: [
            '✓ 连接数据库：建立与深圳环境监测数据库的连接',
            '✓ 构建查询语句：编写SQL查询最近30天的AQI数据',
            '✓ 执行数据检索：获取各监测点的AQI时间序列数据',
            '✓ 数据验证：检查数据完整性和准确性'
          ]
        }
      },
      {
        id: 3,
        title: '3. 数据分析',
        description: '进行趋势和统计分析',
        icon: 'fas fa-chart-line',
        details: {
          title: '数据分析流程',
          items: [
            '✓ 数据清洗：处理缺失值和异常值',
            '✓ 趋势分析：计算AQI的变化趋势和斜率',
            '✓ 统计分析：计算平均值、最大值、最小值等统计指标',
            '✓ 相关性分析：分析AQI与其他环境因素的相关性'
          ]
        }
      },
      {
        id: 4,
        title: '4. 结果生成',
        description: '生成分析报告和可视化',
        icon: 'fas fa-file-alt',
        details: {
          title: '结果生成流程',
          items: [
            '✓ 生成统计图表：创建AQI趋势图和分布图',
            '✓ 撰写分析报告：提供详细的数据分析结果',
            '✓ 提出建议：基于数据分析给出环保建议',
            '✓ 格式化输出：生成用户友好的报告格式'
          ]
        }
      }
    ],
    image: [
      {
        id: 1,
        title: '1. 图像识别',
        description: '识别图像内容和类型',
        icon: 'fas fa-eye',
        details: {
          title: '图像识别流程',
          items: [
            '✓ 图像预处理：调整图像大小和质量',
            '✓ 对象检测：识别图像中的图表和文字',
            '✓ 类型识别：确定为臭氧变化趋势图',
            '✓ 内容解析：提取图像中的关键信息'
          ]
        }
      },
      {
        id: 2,
        title: '2. 数据提取',
        description: '提取图表中的数据',
        icon: 'fas fa-chart-bar',
        details: {
          title: '数据提取流程',
          items: [
            '✓ 坐标识别：识别X轴和Y轴的坐标系统',
            '✓ 数据点提取：从趋势线中提取关键数据点',
            '✓ 数值转换：将像素坐标转换为实际数值',
            '✓ 数据验证：验证提取数据的准确性'
          ]
        }
      },
      {
        id: 3,
        title: '3. 趋势分析',
        description: '分析数据变化趋势',
        icon: 'fas fa-chart-line',
        details: {
          title: '趋势分析流程',
          items: [
            '✓ 数据整理：按时间顺序整理提取的数据',
            '✓ 趋势计算：计算臭氧浓度的变化趋势',
            '✓ 周期性分析：分析数据的周期性变化',
            '✓ 异常检测：识别数据中的异常点'
          ]
        }
      },
      {
        id: 4,
        title: '4. 报告生成',
        description: '生成分析报告',
        icon: 'fas fa-file-alt',
        details: {
          title: '报告生成流程',
          items: [
            '✓ 结果总结：总结臭氧变化的主要特征',
            '✓ 趋势描述：详细描述变化趋势和模式',
            '✓ 原因分析：分析可能的成因和影响因素',
            '✓ 建议提出：基于分析结果提出相关建议'
          ]
        }
      }
    ],
    code: [
      {
        id: 1,
        title: '1. 代码分析',
        description: '分析代码结构和逻辑',
        icon: 'fas fa-code',
        details: {
          title: '代码分析流程',
          items: [
            '✓ 语法检查：检查代码语法错误',
            '✓ 结构分析：分析代码的整体结构和模块',
            '✓ 算法识别：识别使用的算法和数据结构',
            '✓ 复杂度分析：分析时间和空间复杂度'
          ]
        }
      },
      {
        id: 2,
        title: '2. 性能检测',
        description: '检测性能问题和瓶颈',
        icon: 'fas fa-tachometer-alt',
        details: {
          title: '性能检测流程',
          items: [
            '✓ 瓶颈识别：识别性能瓶颈所在',
            '✓ 内存分析：分析内存使用情况和泄漏风险',
            '✓ 执行效率：评估代码执行效率',
            '✓ 资源消耗：分析CPU和其他资源的消耗'
          ]
        }
      },
      {
        id: 3,
        title: '3. 优化建议',
        description: '提供优化建议',
        icon: 'fas fa-lightbulb',
        details: {
          title: '优化建议流程',
          items: [
            '✓ 算法优化：推荐更高效的算法',
            '✓ 代码重构：建议代码重构方案',
            '✓ 并行化：建议并行化处理方案',
            '✓ 缓存策略：推荐合适的缓存策略'
          ]
        }
      },
      {
        id: 4,
        title: '4. 最佳实践',
        description: '提供编码最佳实践',
        icon: 'fas fa-star',
        details: {
          title: '最佳实践流程',
          items: [
            '✓ 代码规范：建议遵循的编码规范',
            '✓ 设计模式：推荐适用的设计模式',
            '✓ 错误处理：建议完善的错误处理机制',
            '✓ 测试策略：推荐单元测试和集成测试策略'
          ]
        }
      }
    ],
    general: [
      {
        id: 1,
        title: '1. 问题解析',
        description: '分析用户问题意图',
        icon: 'fas fa-search',
        details: {
          title: '问题解析流程',
          items: [
            '✓ 问题类型：一般知识查询',
            '✓ 查询对象：技术相关信息',
            '✓ 信息深度：需要详细解答',
            '✓ 输出格式：结构化回答'
          ]
        }
      },
      {
        id: 2,
        title: '2. 知识检索',
        description: '检索内部知识库',
        icon: 'fas fa-database',
        details: {
          title: '知识检索流程',
          items: [
            '✓ 搜索关键词：提取查询关键词',
            '✓ 文档匹配：匹配相关技术文档',
            '✓ 内容筛选：筛选最相关的内容',
            '✓ 信息整合：整合多源信息'
          ]
        }
      },
      {
        id: 3,
        title: '3. 互联网搜索',
        description: '搜索最新技术资料',
        icon: 'fas fa-globe',
        details: {
          title: '互联网搜索流程',
          items: [
            '✓ 实时搜索：搜索最新技术资料',
            '✓ 来源验证：验证信息来源可靠性',
            '✓ 内容更新：确保信息的时效性',
            '✓ 多源整合：整合多个来源的信息'
          ]
        }
      },
      {
        id: 4,
        title: '4. 生成回复',
        description: '整理并生成最终回复',
        icon: 'fas fa-file-alt',
        details: {
          title: '回复生成流程',
          items: [
            '✓ 信息整合：整合检索到的信息',
            '✓ 结构化组织：按照逻辑顺序组织内容',
            '✓ 语言优化：优化表达方式',
            '✓ 质量检查：确保回答的准确性和完整性'
          ]
        }
      }
    ]
  }
  
  processingTasks.value = taskConfig[type as keyof typeof taskConfig].map(task => ({
    ...task,
    status: 'pending' as 'pending' | 'processing' | 'completed',
    showDetails: false
  }))
  
  resultPanels.value = []
  progress.value = 0
}

const startProcessing = async (type: string) => {
  const steps = [
    { step: 1, progress: 25, status: 'completed' },
    { step: 2, progress: 50, status: 'completed' },
    { step: 3, progress: 75, status: 'completed' },
    { step: 4, progress: 100, status: 'completed' }
  ]
  
  for (const stepData of steps) {
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 更新任务状态
    const task = processingTasks.value.find(t => t.id === stepData.step)
    if (task) {
      task.status = stepData.status as 'pending' | 'processing' | 'completed'
      // 如果任务完成，触发滚动到对应结果面板
      if (task.status === 'completed') {
        onTaskCompleted(task.id)
      }
    }
    
    // 更新进度
    progress.value = stepData.progress
    
    // 添加结果面板
    addResultPanel(stepData.step, type)
  }
}

const addResultPanel = (step: number, type: string) => {
  const panel: ResultPanel = {
    id: step,
    title: getPanelTitle(step),
    content: getPanelContent(step, type),
    icon: getPanelIcon(step),
    iconBg: getPanelIconBg(step),
    step: `步骤 ${step}`,
    stepBadge: getPanelStepBadge(step),
    timestamp: new Date(),
    active: true,
    visible: true,
    extraInfo: getPanelExtraInfo(step, type),
    extraInfoClass: getPanelExtraInfoClass(step, type)
  }
  
  resultPanels.value.push(panel)
}

const getPanelTitle = (step: number) => {
  const titles = ['', '问题解析完成', '知识检索完成', '互联网搜索完成', '生成回复完成']
  return titles[step] || ''
}

const getPanelContent = (step: number, type: string) => {
  const contents: Record<string, Record<number, string>> = {
    knowledge: {
      1: `
        <div class="bg-green-50 p-3 rounded-lg">
          <h4 class="font-medium text-green-800 mb-2">解析结果</h4>
          <div class="text-sm text-green-700 space-y-1">
            <div>✓ 问题类型：环境监测专业知识查询</div>
            <div>✓ 查询对象：深圳监测站铜分析方法</div>
            <div>✓ 信息深度：需要详细技术参数和标准依据</div>
            <div>✓ 输出格式：结构化方法列表</div>
          </div>
        </div>
        <div class="bg-blue-50 p-3 rounded-lg">
          <h4 class="font-medium text-blue-800 mb-2">关键实体识别</h4>
          <div class="text-sm text-blue-700">
            <div class="flex flex-wrap gap-2">
              <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">深圳监测站</span>
              <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">地表水</span>
              <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">铜</span>
              <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">分析方法</span>
            </div>
          </div>
        </div>
      `,
      2: `
        <div class="space-y-3">
          <div class="border-l-4 border-blue-400 pl-4 cursor-pointer hover:bg-blue-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">《地表水环境质量标准》(GB 3838-2002)</h4>
            <p class="text-sm text-slate-600 mt-1">规定了地表水中铜的监测方法和标准限值，检测限为0.005mg/L</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded">国家标准</span>
              <span class="text-xs text-slate-500">相关度: 95%</span>
              <i class="fas fa-external-link-alt text-blue-500 text-xs"></i>
            </div>
          </div>
          <div class="border-l-4 border-blue-400 pl-4 cursor-pointer hover:bg-blue-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">《水质 65种元素的测定 电感耦合等离子体质谱法》(HJ 700-2014)</h4>
            <p class="text-sm text-slate-600 mt-1">采用ICP-MS同时测定多种金属元素，铜的检测限为0.0001mg/L</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded">行业标准</span>
              <span class="text-xs text-slate-500">相关度: 92%</span>
              <i class="fas fa-external-link-alt text-blue-500 text-xs"></i>
            </div>
          </div>
        </div>
      `,
      3: `
        <div class="space-y-3">
          <div class="border-l-4 border-yellow-400 pl-4 cursor-pointer hover:bg-yellow-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">深圳环境监测站最新技术进展</h4>
            <p class="text-sm text-slate-600 mt-1">介绍深圳监测站引进的ICP-MS设备及其在重金属检测中的应用...</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-yellow-600 bg-yellow-50 px-2 py-1 rounded">技术文章</span>
              <span class="text-xs text-slate-500">深圳环保网</span>
              <span class="text-xs text-slate-500">2024-01-15</span>
              <i class="fas fa-external-link-alt text-yellow-500 text-xs"></i>
            </div>
          </div>
          <div class="border-l-4 border-yellow-400 pl-4 cursor-pointer hover:bg-yellow-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">水中重金属检测技术最新研究进展</h4>
            <p class="text-sm text-slate-600 mt-1">综述了包括原子吸收、ICP-MS、电化学法等铜检测技术的最新发展...</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-yellow-600 bg-yellow-50 px-2 py-1 rounded">学术论文</span>
              <span class="text-xs text-slate-500">中国环境科学</span>
              <span class="text-xs text-slate-500">2024-01-10</span>
              <i class="fas fa-external-link-alt text-yellow-500 text-xs"></i>
            </div>
          </div>
        </div>
      `,
      4: `
        <div class="space-y-6">
          <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-5 rounded-lg">
            <h4 class="font-semibold text-blue-800 mb-3 flex items-center">
              <i class="fas fa-info-circle mr-2"></i>
              分析方法概述
            </h4>
            <p class="text-sm text-blue-700 leading-relaxed">
              深圳监测站分析地表水中铜主要采用国家标准方法，包括原子吸收分光光度法、电感耦合等离子体质谱法等。这些方法具有高灵敏度、高准确度的特点，能够满足《地表水环境质量标准》(GB 3838-2002)中对铜的检测要求。
            </p>
          </div>
          
          <div>
            <h4 class="font-semibold text-slate-800 mb-4">主要分析方法</h4>
            <div class="space-y-4">
              <div class="border-l-4 border-green-400 pl-4">
                <h5 class="font-medium text-slate-800">1. 原子吸收分光光度法 (AAS)</h5>
                <div class="mt-2 text-sm text-slate-600 space-y-1">
                  <p><strong>检测原理：</strong>利用铜原子在特定波长下的吸收特性进行定量分析</p>
                  <p><strong>检测限：</strong>0.001 mg/L</p>
                  <p><strong>适用范围：</strong>地表水、地下水、饮用水</p>
                  <p><strong>标准依据：</strong>GB/T 7475-1987</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      `
    },
    data: {
      1: `
        <div class="bg-green-50 p-3 rounded-lg">
          <h4 class="font-medium text-green-800 mb-2">需求分析结果</h4>
          <div class="text-sm text-green-700 space-y-1">
            <div>✓ 查询目标：深圳AQI趋势分析</div>
            <div>✓ 时间范围：最近一个月</div>
            <div>✓ 数据类型：空气质量指数时间序列</div>
            <div>✓ 输出要求：趋势分析和可视化</div>
          </div>
        </div>
      `,
      2: `
        <div class="space-y-3">
          <div class="border-l-4 border-blue-400 pl-4">
            <h4 class="font-medium text-slate-800">SQL查询语句</h4>
            <div class="bg-slate-100 p-3 rounded mt-2">
              <code class="text-sm text-slate-700">
                SELECT date, aqi_value, station_name<br>
                FROM air_quality_data<br>
                WHERE station_name LIKE '%深圳%'<br>
                AND date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)<br>
                ORDER BY date ASC;
              </code>
            </div>
          </div>
        </div>
      `,
      3: `
        <div class="space-y-3">
          <div class="bg-blue-50 p-3 rounded-lg">
            <h4 class="font-medium text-blue-800 mb-2">统计分析结果</h4>
            <div class="text-sm text-blue-700 space-y-1">
              <div>• 平均AQI：58.2</div>
              <div>• 最高AQI：95</div>
              <div>• 最低AQI：32</div>
              <div>• 优良天数比例：100%</div>
            </div>
          </div>
        </div>
      `,
      4: `
        <div class="space-y-3">
          <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-5 rounded-lg">
            <h4 class="font-semibold text-purple-800 mb-3">AQI趋势分析报告</h4>
            <p class="text-sm text-slate-700 leading-relaxed">
              最近一个月深圳AQI整体呈现良好趋势，平均值为58.2，全部达到优良标准。建议继续保持现有环保措施，关注特殊气象条件下的空气质量变化。
            </p>
          </div>
        </div>
      `
    },
    image: {
      1: `
        <div class="bg-green-50 p-3 rounded-lg">
          <h4 class="font-medium text-green-800 mb-2">图像识别结果</h4>
          <div class="text-sm text-green-700 space-y-1">
            <div>✓ 图像类型：臭氧浓度时间序列图</div>
            <div>✓ 时间范围：2024年1月</div>
            <div>✓ 数据格式：折线图</div>
            <div>✓ 关键特征：显示明显的周期性变化</div>
          </div>
        </div>
      `,
      2: `
        <div class="space-y-3">
          <div class="bg-blue-50 p-3 rounded-lg">
            <h4 class="font-medium text-blue-800 mb-2">数据提取结果</h4>
            <div class="text-sm text-blue-700 space-y-1">
              <div>• 提取数据点：30个</div>
              <div>• 臭氧浓度范围：45-120 μg/m³</div>
              <div>• 平均浓度：78.5 μg/m³</div>
              <div>• 超标天数：2天</div>
            </div>
          </div>
        </div>
      `,
      3: `
        <div class="space-y-3">
          <div class="bg-yellow-50 p-3 rounded-lg">
            <h4 class="font-medium text-yellow-800 mb-2">趋势分析结果</h4>
            <div class="text-sm text-yellow-700 space-y-1">
              <div>• 总体趋势：先上升后下降</div>
              <div>• 峰值出现：1月15日左右</div>
              <div>• 周期性：呈现7天周期变化</div>
              <div>• 异常点：1月14日数据异常</div>
            </div>
          </div>
        </div>
      `,
      4: `
        <div class="space-y-3">
          <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-5 rounded-lg">
            <h4 class="font-semibold text-purple-800 mb-3">图像分析报告</h4>
            <p class="text-sm text-slate-700 leading-relaxed">
              图像显示2024年1月臭氧浓度呈现先升后降的趋势，月中旬达到峰值。建议在臭氧浓度较高时段加强监测，必要时采取管控措施。
            </p>
          </div>
        </div>
      `
    },
    code: {
      1: `
        <div class="bg-green-50 p-3 rounded-lg">
          <h4 class="font-medium text-green-800 mb-2">代码分析结果</h4>
          <div class="text-sm text-green-700 space-y-1">
            <div>✓ 代码类型：Python数据处理脚本</div>
            <div>✓ 主要功能：数据清洗和分析</div>
            <div>✓ 代码结构：函数式编程</div>
            <div>✓ 算法复杂度：O(n log n)</div>
          </div>
        </div>
      `,
      2: `
        <div class="space-y-3">
          <div class="bg-red-50 p-3 rounded-lg">
            <h4 class="font-medium text-red-800 mb-2">性能问题识别</h4>
            <div class="text-sm text-red-700 space-y-1">
              <div>• 内存泄漏：未正确关闭文件连接</div>
              <div>• 重复计算：循环中重复计算相同值</div>
              <div>• 低效算法：使用嵌套循环查找</div>
              <div>• 缺少缓存：重复读取外部数据</div>
            </div>
          </div>
        </div>
      `,
      3: `
        <div class="space-y-3">
          <div class="bg-yellow-50 p-3 rounded-lg">
            <h4 class="font-medium text-yellow-800 mb-2">优化建议</h4>
            <div class="text-sm text-yellow-700 space-y-1">
              <div>• 使用上下文管理器：with语句管理资源</div>
              <div>• 算法优化：使用字典查找替代循环</div>
              <div>• 内存优化：使用生成器替代列表</div>
              <div>• 添加缓存：使用functools.lru_cache</div>
            </div>
          </div>
        </div>
      `,
      4: `
        <div class="space-y-3">
          <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-5 rounded-lg">
            <h4 class="font-semibold text-purple-800 mb-3">最佳实践建议</h4>
            <p class="text-sm text-slate-700 leading-relaxed">
              建议遵循PEP 8编码规范，添加类型注解，编写单元测试，使用虚拟环境管理依赖。推荐使用pandas进行数据处理，matplotlib进行可视化。
            </p>
          </div>
        </div>
      `
    },
    general: {
      1: `
        <div class="bg-green-50 p-3 rounded-lg">
          <h4 class="font-medium text-green-800 mb-2">解析结果</h4>
          <div class="text-sm text-green-700 space-y-1">
            <div>✓ 问题类型：一般知识查询</div>
            <div>✓ 查询对象：技术相关信息</div>
            <div>✓ 信息深度：需要详细解答</div>
            <div>✓ 输出格式：结构化回答</div>
          </div>
        </div>
      `,
      2: `
        <div class="space-y-3">
          <div class="border-l-4 border-blue-400 pl-4 cursor-pointer hover:bg-blue-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">技术文档库</h4>
            <p class="text-sm text-slate-600 mt-1">找到相关技术文档</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded">技术文档</span>
              <span class="text-xs text-slate-500">相关度: 85%</span>
            </div>
          </div>
        </div>
      `,
      3: `
        <div class="space-y-3">
          <div class="border-l-4 border-yellow-400 pl-4 cursor-pointer hover:bg-yellow-50 p-2 rounded transition-colors">
            <h4 class="font-medium text-slate-800">最新技术资料</h4>
            <p class="text-sm text-slate-600 mt-1">找到相关技术文章</p>
            <div class="flex items-center space-x-2 mt-2">
              <span class="text-xs text-yellow-600 bg-yellow-50 px-2 py-1 rounded">技术文章</span>
              <span class="text-xs text-slate-500">2024-01-15</span>
            </div>
          </div>
        </div>
      `,
      4: `
        <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-5 rounded-lg">
          <h4 class="font-semibold text-purple-800 mb-3">最终回答</h4>
          <p class="text-sm text-slate-700 leading-relaxed">
            基于对您问题的分析，我为您提供了详细的解答。答案综合了内部知识库和互联网搜索的结果，确保信息的准确性和时效性。
          </p>
        </div>
      `
    }
  }
  
  return contents[type]?.[step] || ''
}

const getPanelIcon = (step: number) => {
  const icons = ['', 'fas fa-search', 'fas fa-database', 'fas fa-globe', 'fas fa-graduation-cap']
  return icons[step] || ''
}

const getPanelIconBg = (step: number) => {
  const bgs = ['', 'bg-green-100', 'bg-blue-100', 'bg-yellow-100', 'bg-purple-100']
  return bgs[step] || ''
}

const getPanelStepBadge = (step: number) => {
  const badges = ['', 'bg-green-100 text-green-700', 'bg-blue-100 text-blue-700', 'bg-yellow-100 text-yellow-700', 'bg-purple-100 text-purple-700']
  return badges[step] || ''
}

const getPanelExtraInfo = (step: number, type: string) => {
  const infos: Record<string, string[]> = {
    knowledge: ['', '', '找到 5 篇相关文档', '找到 8 篇相关文章', '最终答案'],
    data: ['', '', '查询到 30 条记录', '分析完成', '生成报告'],
    image: ['', '', '提取 30 个数据点', '趋势分析完成', '分析报告'],
    code: ['', '', '发现 4 个问题', '提供 6 条建议', '最佳实践'],
    general: ['', '', '找到 3 篇相关文档', '找到 5 篇相关文章', '最终答案']
  }
  return infos[type]?.[step] || ''
}

const getPanelExtraInfoClass = (step: number, type: string) => {
  const classes: Record<string, string[]> = {
    knowledge: ['', '', 'text-blue-600', 'text-yellow-600', 'text-purple-600'],
    data: ['', '', 'text-blue-600', 'text-yellow-600', 'text-purple-600'],
    image: ['', '', 'text-blue-600', 'text-yellow-600', 'text-purple-600'],
    code: ['', '', 'text-blue-600', 'text-yellow-600', 'text-purple-600'],
    general: ['', '', 'text-blue-600', 'text-yellow-600', 'text-purple-600']
  }
  return classes[type]?.[step] || ''
}

const getTaskClasses = (task: ProcessingTask) => {
  const base = 'border-2 bg-white cursor-pointer'
  switch (task.status) {
    case 'completed':
      return `${base} border-green-200 completed-task`
    case 'processing':
      return `${base} border-blue-200 active`
    default:
      return `${base} border-slate-200`
  }
}

const getTaskIconClasses = (task: ProcessingTask) => {
  switch (task.status) {
    case 'completed':
      return 'bg-green-500'
    case 'processing':
      return 'bg-blue-500'
    default:
      return 'bg-slate-300'
  }
}

const getTaskIcon = (task: ProcessingTask) => {
  if (task.status === 'completed') {
    return 'fas fa-check'
  }
  return task.icon
}

const getTaskStatus = (task: ProcessingTask) => {
  const statuses = {
    'pending': '等待中',
    'processing': '处理中',
    'completed': '已完成'
  }
  return statuses[task.status] || ''
}

const getTaskStatusClasses = (task: ProcessingTask) => {
  const classes = {
    'pending': 'text-slate-500',
    'processing': 'text-blue-600',
    'completed': 'text-green-600'
  }
  return classes[task.status] || ''
}

const getTaskDetailTitle = (task: ProcessingTask) => {
  return task.details.title
}

const getTaskDetailItems = (task: ProcessingTask) => {
  return task.details.items
}

const handleTaskClick = (task: ProcessingTask) => {
  if (task.status === 'completed') {
    // 显示/隐藏任务详情
    task.showDetails = !task.showDetails
    
    // 高亮对应的结果面板
    resultPanels.value.forEach(panel => {
      panel.active = panel.id === task.id
    })
    
    // 滚动到对应的结果面板
    scrollToResultPanel(task.id)
  }
}

const handleResultPanelClick = (panel: ResultPanel) => {
  // 高亮对应的处理任务
  const task = processingTasks.value.find(t => t.id === panel.id)
  if (task && task.status === 'completed') {
    task.showDetails = true
    // 滚动到对应的处理任务
    setTimeout(() => {
      const taskElement = document.querySelector(`[data-task="${task.id}"]`)
      if (taskElement) {
        taskElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
    }, 100)
  }
  
  // 高亮结果面板
  resultPanels.value.forEach(p => {
    p.active = p.id === panel.id
  })
}

// 滚动到指定的结果面板
const scrollToResultPanel = (panelId: number) => {
  setTimeout(() => {
    const panelElement = document.querySelector(`[data-result="${panelId}"]`)
    if (panelElement) {
      panelElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
      // 触发面板点击事件以高亮对应的任务
      const panel = resultPanels.value.find(p => p.id === panelId)
      if (panel) {
        handleResultPanelClick(panel)
      }
    }
  }, 100)
}

// 当处理任务完成时，自动滚动到对应的结果面板
const onTaskCompleted = (taskId: number) => {
  const panel = resultPanels.value.find(p => p.id === taskId)
  if (panel) {
    scrollToResultPanel(taskId)
  }
}

// 语音输入功能
const isRecording = ref(false)
let recognitionInstance: any = null

const startVoiceInput = () => {
  if (isRecording.value) {
    // 如果正在录音，则停止录音
    stopVoiceInput()
    return
  }
  
  if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
    // @ts-ignore
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    recognitionInstance = new SpeechRecognition()
    
    recognitionInstance.lang = 'zh-CN'
    recognitionInstance.continuous = false
    recognitionInstance.interimResults = false
    
    recognitionInstance.onstart = () => {
      console.log('语音识别开始')
      isRecording.value = true
    }
    
    recognitionInstance.onresult = (event: any) => {
      const transcript = event.results[0][0].transcript
      newMessage.value = transcript
    }
    
    recognitionInstance.onerror = (event: any) => {
      console.error('语音识别错误:', event.error)
      isRecording.value = false
      recognitionInstance = null
    }
    
    recognitionInstance.onend = () => {
      console.log('语音识别结束')
      isRecording.value = false
      recognitionInstance = null
    }
    
    recognitionInstance.start()
  } else {
    console.log('浏览器不支持语音识别')
  }
}

const stopVoiceInput = () => {
  if (recognitionInstance) {
    try {
      recognitionInstance.stop()
      recognitionInstance = null
    } catch (error) {
      console.error('停止语音识别失败:', error)
    }
  }
  isRecording.value = false
}

// 上传图片功能
const uploadImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      console.log('上传图片:', file.name)
    }
  }
  input.click()
}

// 上传文件功能
const uploadFile = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '*.*'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      console.log('上传文件:', file.name)
    }
  }
  input.click()
}

// 代码片段功能
const insertCodeSnippet = () => {
  newMessage.value += '\n```\n// 在这里输入您的代码\n```\n'
}

// 清空对话功能
const clearConversation = () => {
  if (confirm('确定要清空当前对话吗？')) {
    messages.value = []
    processingTasks.value = []
    resultPanels.value = []
    selectedConversation.value = null
  }
}

const formatDate = (date: Date | string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatTime = (date: Date | string) => {
  return new Date(date).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const goToSettings = () => {
  router.push('/settings')
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 生命周期
onMounted(() => {
  // 初始化示例对话
  conversations.value = [
    { 
      id: 1, 
      title: '深圳监测站分析方法', 
      created_at: new Date(Date.now() - 86400000), 
      type: 'knowledge' 
    },
    { 
      id: 2, 
      title: '深圳AQI趋势分析', 
      created_at: new Date(Date.now() - 172800000), 
      type: 'data' 
    },
    { 
      id: 3, 
      title: '臭氧变化趋势图分析', 
      created_at: new Date(Date.now() - 259200000), 
      type: 'image' 
    },
    { 
      id: 4, 
      title: 'Python代码性能分析', 
      created_at: new Date(Date.now() - 345600000), 
      type: 'code' 
    }
  ]
  
  // 自动加载第一个对话
  if (conversations.value.length > 0) {
    selectConversation(conversations.value[0])
  }
})
</script>

<style scoped>
/* 全局滚动条控制 */
* {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

*::-webkit-scrollbar {
  display: none;
}

/* 自定义滚动条 - 重新启用 */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
  display: block;
}

.custom-scrollbar::-webkit-scrollbar-track {
  display: block;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  display: block;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  display: block;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 防止横向滚动 */
.no-x-overflow {
  overflow-x: hidden;
}

/* 确保内容不溢出 */
.content-wrap {
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
}

/* 防止表格和代码块横向溢出 */
.table-container {
  overflow-x: auto;
  max-width: 100%;
}

.code-container {
  overflow-x: auto;
  max-width: 100%;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 麦克风录音动画效果 */
.voice-recording {
  animation: voicePulse 1.5s ease-in-out infinite;
}

@keyframes voicePulse {
  0%, 100% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
    background-color: rgb(239, 68, 68);
  }
  50% {
    box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
    background-color: rgb(220, 38, 38);
  }
}

.voice-recording i {
  color: white !important;
  animation: voiceIcon 1.5s ease-in-out infinite;
}

@keyframes voiceIcon {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

/* 侧边栏动画 */
.sidebar {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  width: 15%;
  min-width: 0;
  overflow: hidden;
}

.sidebar-collapsed {
  width: 64px !important;
}

/* 悬停提示 */
.tooltip {
  position: absolute;
  left: 100%;
  top: 50%;
  transform: translateY(-50%);
  background: #1f2937;
  color: white;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
  margin-left: 10px;
  z-index: 1000;
}

.tooltip::before {
  content: '';
  position: absolute;
  right: 100%;
  top: 50%;
  transform: translateY(-50%);
  border: 6px solid transparent;
  border-right-color: #1f2937;
}

.has-tooltip:hover .tooltip {
  opacity: 1;
}

/* 文本淡入淡出 */
.fade-text {
  transition: opacity 0.3s ease-in-out;
}

.fade-text.hidden {
  opacity: 0;
  pointer-events: none;
}

/* 玻璃态效果 */
.glass-effect {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 进度条 */
.progress-bar {
  height: 3px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 2px;
  transition: width 0.3s ease;
}

/* 时间戳样式 */
.timestamp {
  font-size: 0.75rem;
  opacity: 0.7;
}

.user-timestamp {
  text-align: right;
}

/* 处理节点动画 */
.processing-node {
  transition: all 0.3s ease;
  animation: todoFadeIn 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.processing-node:hover {
  transform: translateX(8px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.processing-node.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.processing-node.active .task-details {
  border-left-color: #667eea;
}

.processing-node.completed-task {
  border-left: 3px solid #10b981 !important;
  cursor: pointer;
}

.processing-node.completed-task:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

@keyframes todoFadeIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 任务详情样式 */
.task-details {
  margin-top: 12px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 3px solid #e2e8f0;
  font-size: 12px;
  line-height: 1.5;
  color: #475569;
  display: none;
}

.task-details.show {
  display: block;
  animation: slideDown 0.3s ease-out;
}

.task-details h4 {
  font-weight: 600;
  margin-bottom: 8px;
  color: #1f2937;
}

.task-details ul {
  list-style: none;
  padding: 0;
}

.task-details li {
  margin-bottom: 4px;
  padding-left: 16px;
  position: relative;
}

.task-details li::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #6b7280;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
  }
  to {
    opacity: 1;
    max-height: 200px;
  }
}

/* 加载动画 */
.loading-dots {
  display: flex;
  gap: 2px;
}

.loading-dots span {
  width: 4px;
  height: 4px;
  background: white;
  border-radius: 50%;
  animation: loadingDots 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loadingDots {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 结果面板动画 */
.result-panel {
  transition: all 0.3s ease;
  border: 2px solid transparent;
  animation: slideInUp 0.5s ease-out;
}

.result-panel:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 附件按钮 */
.attachment-btn {
  transition: all 0.2s ease;
  position: relative;
}

.attachment-btn:hover {
  transform: translateY(-2px);
}

.attachment-btn::after {
  content: attr(data-tooltip);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: #1f2937;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
  margin-bottom: 4px;
}

.attachment-btn:hover::after {
  opacity: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-collapsed {
    width: 0 !important;
  }
  
  .sidebar-expanded {
    width: 100% !important;
    position: absolute;
    z-index: 50;
    height: 100%;
  }
}
</style>